/**
 * All rights Reserved, Designed By www.cyunsoft.com
 *
 * @Title: RountPageOfficeController.java
 * @Package com.core136.controller.file
 * @Description: (用一句话描述该文件做什么)
 * @author: 稠云信息
 * @date: 2019年5月17日 下午4:44:47
 * @version V1.0
 * @Copyright: 2019 www.cyunsoft.com Inc. All rights reserved.
 * 注意：本内容仅限于江苏稠云信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.core136.controller.file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.core136.bean.account.Account;
import com.core136.bean.account.UserInfo;
import com.core136.bean.file.Attach;
import com.core136.bean.file.NetDisk;
import com.core136.bean.file.PublicFile;
import com.core136.common.enums.GobalConstant;
import com.core136.common.retdataunit.RetDataTools;
import com.core136.common.utils.FileAESUtils;
import com.core136.common.utils.SysTools;
import com.core136.service.account.AccountService;
import com.core136.service.file.AttachService;
import com.core136.service.file.NetDiskService;
import com.core136.service.file.PublicFileService;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PDFCtrl;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author lsq
 * @ClassName: RountPageOfficeController
 * @Description:(这里用一句话描述这个类的作用)
 * @author: 稠云信息
 * @date: 2019年5月17日 下午4:44:47
 * @Copyright: 2019 www.cyunsoft.com Inc. All rights reserved.
 * 注意：本内容仅限于江苏稠云信息技术有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
@RestController
@RequestMapping("/office")
public class RoutePageOfficeController {
    private AttachService attachService;

    @Autowired
    public void setAttachService(AttachService attachService) {
        this.attachService = attachService;
    }

    private NetDiskService netDiskService;

    @Autowired
    public void setNetDiskService(NetDiskService netDiskService) {
        this.netDiskService = netDiskService;
    }

    private AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    private PublicFileService publicFileService;

    @Autowired
    public void setPublicFileService(PublicFileService publicFileService) {
        this.publicFileService = publicFileService;
    }

    @Value("${app.attach.encryption}")
    private String encryption;
    @Value("${app.attachpath}")
    private String attachpath;
    private static final String ALGORITHM = "AES";

    /**
     * @param request
     * @param attach
     * @param openModeType
     * @param fileId
     * @return ModelAndView
     * @Title: openSwOfd
     * @Description:  数科OFD文件打开
     */
    @RequestMapping(value = "/ofd/openswofd", method = RequestMethod.GET)
    public ModelAndView openSwOfd(HttpServletRequest request, Attach attach, String openModeType, String fileId) {
        ModelAndView mv = new ModelAndView("app/core/suwell/openofd");
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        attach = attachService.selectOne(attach);
        String mHttpUrlName = request.getRequestURI();
        String mScriptName = request.getServletPath();
        String mServerUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + mHttpUrlName.substring(0, mHttpUrlName.lastIndexOf(mScriptName));//取得OfficeServer文件的完整URL
        mv.addObject("mServerUrl", mServerUrl);
        mv.addObject("fileId", fileId);
        mv.addObject("sessionId", request.getSession().getId());
        mv.addObject("userName", userInfo.getUserName());
        mv.addObject("attach", attach);
        String pointFlag = "0";
        String downFlag = "0";
        if (openModeType.equals("1")) {
            //只读模式
            mv.addObject("editType", "0");
        } else if (openModeType.equals("2")) {
            //打印模式
            mv.addObject("editType", "0");
            pointFlag = "1";
        } else if (openModeType.equals("3")) {
            //打印模式,下载模式
            mv.addObject("editType", "0");
            pointFlag = "1";
            downFlag = "1";
        } else if (openModeType.equals("4")) {
            //痕迹保留模式
            mv.addObject("editType", "2");
            pointFlag = "1";
        } else if (openModeType.equals("5")) {
            mv.addObject("editType", "2");
            pointFlag = "1";
        }
        mv.addObject("pointFlag", pointFlag);
        mv.addObject("downFlag", downFlag);
        return mv;
    }


    /**
     * @param request
     * @param attach
     * @param openModeType
     * @param fileId
     * @return ModelAndView
     * @Title: openFxOfd
     * @Description:  福昕OFD打开方式
     */
    @RequestMapping(value = "/ofd/openfxofd", method = RequestMethod.GET)
    public ModelAndView openFxOfd(HttpServletRequest request, Attach attach, String openModeType, String fileId) {
        ModelAndView mv = new ModelAndView("app/core/fxofd/fxofdopen");
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        attach = attachService.selectOne(attach);
        String mHttpUrlName = request.getRequestURI();
        String mScriptName = request.getServletPath();
        String mServerUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + mHttpUrlName.substring(0, mHttpUrlName.lastIndexOf(mScriptName));//取得OfficeServer文件的完整URL
        mv.addObject("mServerUrl", mServerUrl);
        mv.addObject("fileId", fileId);
        mv.addObject("sessionId", request.getSession().getId());
        mv.addObject("userName", userInfo.getUserName());
        mv.addObject("attach", attach);
        String pointFlag = "0";
        String downFlag = "0";
        if (openModeType.equals("1")) {
            //只读模式
            mv.addObject("editType", "0");
        } else if (openModeType.equals("2")) {
            //打印模式
            mv.addObject("editType", "0");
            pointFlag = "1";
        } else if (openModeType.equals("3")) {
            //打印模式,下载模式
            mv.addObject("editType", "0");
            pointFlag = "1";
            downFlag = "1";
        } else if (openModeType.equals("4")) {
            //痕迹保留模式
            mv.addObject("editType", "2");
            pointFlag = "1";
        } else if (openModeType.equals("5")) {
            mv.addObject("editType", "2");
            pointFlag = "1";
        }
        mv.addObject("pointFlag", pointFlag);
        mv.addObject("downFlag", downFlag);
        return mv;
    }

    /**
     * @param attachId
     * @param sessionId
     * @param request
     * @param response
     * @throws Exception void
     * @Title: ofdSwSaveFile
     * @Description:  数科ofd保存
     */
    @RequestMapping(value = "/ofdSwSave", method = RequestMethod.POST)
    public void ofdSwSaveFile(String attachId, String sessionId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        FileInputStream sourceFileIn = null;
        FileOutputStream fileOutputStream = null;
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo(sessionId);
        if (userInfo != null) {
            try {
                Attach attach = new Attach();
                attach.setAttachId(attachId);
                attach = attachService.selectOne(attach);
                String extName = attach.getOldName();
                int dot = extName.lastIndexOf('.');
                if (dot > -1 && dot < extName.length() - 1) {
                    extName = extName.substring(dot);
                } else {
                    extName = "";
                }

                String filePath = attachpath+attach.getPath();
                File targetFile = new File(filePath);
                filePath = targetFile.getAbsoluteFile().toString();
                String sourceFilePath = filePath;
                if (!extName.isEmpty()) {
                    dot = filePath.lastIndexOf('.');
                    if ((dot > -1) && (dot < (filePath.length()))) {
                        filePath = filePath.substring(0, dot);
                    }
                    filePath = filePath + extName;
                }
                //备份修改前的文件版本
                String oldName = SysTools.randFileName(attach.getOldName());
                String oldPath = filePath.substring(0, filePath.lastIndexOf(File.separator)) + File.separator + oldName;
                Attach oldAttach = new Attach();
                BeanUtils.copyProperties(attach, oldAttach);
                oldAttach.setAttachId(SysTools.getGUID());
                oldAttach.setNewName(oldName);
                oldAttach.setPath(oldPath);
                oldAttach.setSourceAttachId(attachId);
                attachService.insert(oldAttach);
                //更新最新文件版本
                sourceFileIn = new FileInputStream(new File(sourceFilePath));
                fileOutputStream = new FileOutputStream(new File(oldPath));
                IOUtils.copy(sourceFileIn, fileOutputStream);//备份文件
                Collection<Part> parts = null;
                try {
                    parts = request.getParts();
                } catch (IOException e) {
                    RetDataTools.Error(e.getMessage());
                } catch (ServletException e) {
                    RetDataTools.Error(e.getMessage());
                }
                if (null != parts && parts.size() > 0) {
                    Iterator<Part> it = parts.iterator();
                    while (it.hasNext()) {
                        Part part = it.next();
                        String fileName = getFileName(part);
                        if ("".equals(fileName)) {
                            continue;
                        }
                        int oldVersion = Integer.parseInt(attach.getVersion().replace(".", ""));
                        String encryptKey = "";
                        if (encryption.equals("1")) {
                            encryptKey = FileAESUtils.getSecretKey();
                        }
                        String newVersion = StringUtils.join(String.valueOf(oldVersion + 1).toCharArray(), '.');
                        attach.setVersion(newVersion);
                        attach.setExtName(extName);
                        attach.setOldName(attach.getOldName().substring(0, attach.getOldName().lastIndexOf(".")) + extName);
                        attach.setNewName(attach.getNewName().substring(0, attach.getNewName().lastIndexOf(".")) + extName);
                        attach.setPath(filePath);
                        attach.setEncryptKey(encryptKey);
                        attach.setFileSize(Long.valueOf(part.getInputStream().available()));
                        attach.setCreateAccount(userInfo.getAccountId());
                        attach.setUpTime(SysTools.getTime("yyyy-MM-dd HH:mm:ss"));
                        Example example = new Example(Attach.class);
                        example.createCriteria().andEqualTo("orgId", userInfo.getOrgId()).andEqualTo("attachId", attach.getAttachId());
                        attachService.updateAttach(attach, example);
                        if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                            FileAESUtils.encryptFile(encryptKey, part.getInputStream(), filePath);
                        } else {
                            part.write(filePath);// 写入服务器
                        }
                    }
                }
            } catch (IOException e) {

            }finally {
                IOUtils.closeQuietly(sourceFileIn);
                IOUtils.closeQuietly(fileOutputStream);
            }
        }
    }

    public static String getFileName(Part part)// 得到客户端的上传的文件的文件名
    {
        String fname = "";
        String hvalue = part.getHeader("Content-Disposition");// 得到这个报头中的信息
        // form-data; name="pic"; filename="hello.txt"（这里是这个报头中的信息）
        Pattern pattern = Pattern.compile("(form-data; name=\"(.*?)\"; filename=\"(.*?)\")");// 用正则表达式来获取文件名
        Matcher mach = pattern.matcher(hvalue);// 匹配
        if (mach.find()) {
            fname = mach.group(3);// 第三组，括号分组
        }
        return fname;
    }

    /**
     * @param attachId
     * @param sessionId
     * @param request
     * @throws IllegalAccessException
     * @throws InvocationTargetException void
     * @throws IOException
     * @Title: ofdSaveFile
     * @Description:  保存ofd文件
     */
    @RequestMapping(value = "/ofdSave", method = RequestMethod.POST)
    public void ofdSaveFile(String attachId, String sessionId, HttpServletRequest request) throws Exception {
        InputStream in = null;
        FileInputStream sourceFileIn = null;
        FileOutputStream fileOutputStream = null;
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo(sessionId);
        if (userInfo != null) {
            in = request.getInputStream();
            Attach attach = new Attach();
            attach.setAttachId(attachId);
            attach = attachService.selectOne(attach);
            String extName = attach.getOldName();
            int dot = extName.lastIndexOf('.');
            if (dot > -1 && dot < extName.length() - 1) {
                extName = extName.substring(dot);
            } else {
                extName = "";
            }

            String filePath = attachpath+attach.getPath();
            File targetFile = new File(filePath);
            filePath = targetFile.getAbsoluteFile().toString();
            String sourceFilePath = filePath;
            if (!extName.isEmpty()) {
                dot = filePath.lastIndexOf('.');
                if ((dot > -1) && (dot < (filePath.length()))) {
                    filePath = filePath.substring(0, dot);
                }
                filePath = filePath + extName;
            }

            //备份修改前的文件版本
            String oldName = SysTools.randFileName(attach.getOldName());
            String oldPath = filePath.substring(0, filePath.lastIndexOf(File.separator)) + File.separator + oldName;
            Attach oldAttach = new Attach();
            BeanUtils.copyProperties(attach, oldAttach);
            oldAttach.setAttachId(SysTools.getGUID());
            oldAttach.setNewName(oldName);
            oldAttach.setPath(oldPath);
            oldAttach.setSourceAttachId(attachId);
            attachService.insert(oldAttach);
            //更新最新文件版本
            int oldVersion = Integer.parseInt(attach.getVersion().replace(".", ""));
            String encryptKey = "";
            if (encryption.equals("1")) {
                encryptKey = FileAESUtils.getSecretKey();
            }
            String newVersion = org.apache.commons.lang3.StringUtils.join(String.valueOf(oldVersion + 1).toCharArray(), '.');
            attach.setVersion(newVersion);
            attach.setExtName(extName);
            attach.setOldName(attach.getOldName().substring(0, attach.getOldName().lastIndexOf(".")) + extName);
            attach.setNewName(attach.getNewName().substring(0, attach.getNewName().lastIndexOf(".")) + extName);
            attach.setPath(filePath);
            attach.setEncryptKey(encryptKey);
            attach.setFileSize(Long.valueOf(in.available()));
            attach.setCreateAccount(userInfo.getAccountId());
            attach.setUpTime(SysTools.getTime("yyyy-MM-dd HH:mm:ss"));
            Example example = new Example(Attach.class);
            example.createCriteria().andEqualTo("orgId", userInfo.getOrgId()).andEqualTo("attachId", attach.getAttachId());
            attachService.updateAttach(attach, example);
            try {
                sourceFileIn = new FileInputStream(new File(sourceFilePath));
                fileOutputStream = new FileOutputStream(new File(oldPath));
                IOUtils.copy(sourceFileIn, fileOutputStream);//备份文件
                sourceFileIn.close();
                fileOutputStream.close();
                if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                    FileAESUtils.encryptFile(encryptKey, in, filePath);
                } else {
                    FileOutputStream fileOutputStream1 = new FileOutputStream(new File(filePath));
                    IOUtils.copy(in, fileOutputStream1);//保存修改后的文件
                    in.close();
                    fileOutputStream1.close();
                }
            } catch (IOException e) {

            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(sourceFileIn);
                IOUtils.closeQuietly(fileOutputStream);
            }
        }
    }


    /**
     * @param request
     * @param openModeType
     * @param fileId
     * @return ModelAndView
     * @Title: openWpsWord
     * @Description:  wpsjs插件打开文档
     */
    @RequestMapping(value = "/wps/openword", method = RequestMethod.GET)
    public ModelAndView openWpsWord(HttpServletRequest request,String openModeType, String fileId) {
        ModelAndView mv = new ModelAndView("app/core/wps/openword");
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        String mHttpUrlName = request.getRequestURI();
        String mScriptName = request.getServletPath();
        String mServerUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + mHttpUrlName.substring(0, mHttpUrlName.lastIndexOf(mScriptName));//取得OfficeServer文件的完整URL
        mv.addObject("mServerUrl", mServerUrl);
        mv.addObject("fileId", fileId);
        mv.addObject("sessionId", request.getSession().getId());
        mv.addObject("userName", userInfo.getUserName());
        String pointFlag = "0";
        String downFlag = "0";
        if (openModeType.equals("1")) {
            //只读模式
            mv.addObject("editType", "0");
        } else if (openModeType.equals("2")) {
            //打印模式
            mv.addObject("editType", "0");
            pointFlag = "1";
        } else if (openModeType.equals("3")) {
            //打印模式,下载模式
            mv.addObject("editType", "0");
            pointFlag = "1";
            downFlag = "1";
        } else if (openModeType.equals("4")) {
            //痕迹保留模式
            mv.addObject("editType", "2");
            pointFlag = "1";
        } else if (openModeType.equals("5")) {
            mv.addObject("editType", "2");
            pointFlag = "1";
        }
        mv.addObject("pointFlag", pointFlag);
        mv.addObject("downFlag", downFlag);
        return mv;
    }

    @RequestMapping(value = "/wps/openexcel", method = RequestMethod.GET)
    public ModelAndView openWpsExcel(HttpServletRequest request,String openModeType, String fileId) {
        ModelAndView mv = new ModelAndView("app/core/wps/openexcel");
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        String mHttpUrlName = request.getRequestURI();
        String mScriptName = request.getServletPath();
        String mServerUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + mHttpUrlName.substring(0, mHttpUrlName.lastIndexOf(mScriptName));//取得OfficeServer文件的完整URL
        mv.addObject("mServerUrl", mServerUrl);
        mv.addObject("fileId", fileId);
        mv.addObject("sessionId", request.getSession().getId());
        mv.addObject("userName", userInfo.getUserName());
        String pointFlag = "0";
        String downFlag = "0";
        if (openModeType.equals("1")) {
            //只读模式
            mv.addObject("editType", "0");
        } else if (openModeType.equals("2")) {
            //打印模式
            mv.addObject("editType", "0");
            pointFlag = "1";
        } else if (openModeType.equals("3")) {
            //打印模式,下载模式
            mv.addObject("editType", "0");
            pointFlag = "1";
            downFlag = "1";
        } else if (openModeType.equals("4")) {
            //痕迹保留模式
            mv.addObject("editType", "2");
            pointFlag = "1";
        }
        mv.addObject("pointFlag", pointFlag);
        mv.addObject("downFlag", downFlag);
        return mv;
    }

    @RequestMapping(value = "/wps/openppt", method = RequestMethod.GET)
    public ModelAndView openWpsPpt(HttpServletRequest request, Attach attach, String openModeType, String fileId) {
        ModelAndView mv = new ModelAndView("app/core/wps/openppt");
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        attach = attachService.selectOne(attach);
        String mHttpUrlName = request.getRequestURI();
        String mScriptName = request.getServletPath();
        String mServerUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + mHttpUrlName.substring(0, mHttpUrlName.lastIndexOf(mScriptName));//取得OfficeServer文件的完整URL
        mv.addObject("mServerUrl", mServerUrl);
        mv.addObject("fileId", fileId);
        mv.addObject("sessionId", request.getSession().getId());
        mv.addObject("userName", userInfo.getUserName());
        mv.addObject("attach", attach);
        String pointFlag = "0";
        String downFlag = "0";
        if (openModeType.equals("1")) {
            //只读模式
            mv.addObject("editType", "0");
        } else if (openModeType.equals("2")) {
            //打印模式
            mv.addObject("editType", "0");
            pointFlag = "1";
        } else if (openModeType.equals("3")) {
            //打印模式,下载模式
            mv.addObject("editType", "0");
            pointFlag = "1";
            downFlag = "1";
        } else if (openModeType.equals("4")) {
            //痕迹保留模式
            mv.addObject("editType", "2");
            pointFlag = "1";
        }
        if (openModeType.equals("5")) {
            //痕迹保留模式
            mv.addObject("editType", "2");
            pointFlag = "1";
        }
        mv.addObject("pointFlag", pointFlag);
        mv.addObject("downFlag", downFlag);
        return mv;
    }

    @RequestMapping(value = "/wpsSave", method = RequestMethod.POST)
    public void wpsSaveFile(MultipartFile file, String attachId, String sessionId) throws Exception {
        FileInputStream sourceFileIn = null;
        FileOutputStream fileOutputStream = null;
        InputStream sourceFileIn1 = null;
        FileOutputStream fileOutputStream1 = null;
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo(sessionId);
        if (userInfo != null) {
            String extName = file.getOriginalFilename();
            int dot = extName.lastIndexOf('.');
            if (dot > -1 && dot < extName.length() - 1) {
                extName = extName.substring(dot);
            } else {
                extName = "";
            }
            Attach attach = new Attach();
            attach.setAttachId(attachId);
            attach = attachService.selectOne(attach);
            String filePath = attachpath+attach.getPath();
            String oldPath = attach.getPath();
            File targetFile = new File(filePath);
            filePath = targetFile.getAbsoluteFile().toString();
            String sourceFilePath = filePath;
            if (!extName.isEmpty()) {
                dot = filePath.lastIndexOf('.');
                if ((dot > -1) && (dot < (filePath.length()))) {
                    filePath = filePath.substring(0, dot);
                }
                filePath = filePath + extName;
            }

            //备份修改前的文件版本
            String oldName = SysTools.randFileName(attach.getOldName());
            oldPath = oldPath.substring(0, oldPath.lastIndexOf(File.separator)) + File.separator + oldName;
            Attach oldAttach = new Attach();
            BeanUtils.copyProperties(attach, oldAttach);
            oldAttach.setAttachId(SysTools.getGUID());
            oldAttach.setNewName(oldName);
            oldAttach.setPath(oldPath);
            oldAttach.setSourceAttachId(attachId);
            attachService.insert(oldAttach);
            //更新最新文件版本
            String encryptKey = "";
            if (encryption.equals("1")) {
                encryptKey = FileAESUtils.getSecretKey();
            }
            int oldVersion = Integer.parseInt(attach.getVersion().replace(".", ""));
            String newVersion = StringUtils.join(String.valueOf(oldVersion + 1).toCharArray(), '.');
            attach.setVersion(newVersion);
            attach.setExtName(extName);
            attach.setFileSize(file.getSize());
            attach.setOldName(attach.getOldName().substring(0, attach.getOldName().lastIndexOf(".")) + extName);
            attach.setNewName(attach.getNewName().substring(0, attach.getNewName().lastIndexOf(".")) + extName);
            attach.setEncryptKey(encryptKey);
            attach.setCreateAccount(userInfo.getAccountId());
            attach.setUpTime(SysTools.getTime("yyyy-MM-dd HH:mm:ss"));
            Example example = new Example(Attach.class);
            example.createCriteria().andEqualTo("orgId", userInfo.getOrgId()).andEqualTo("attachId", attach.getAttachId());
            attachService.updateAttach(attach, example);
            try {
                sourceFileIn = new FileInputStream(new File(sourceFilePath));
                fileOutputStream = new FileOutputStream(new File(attachpath+oldPath));
                IOUtils.copy(sourceFileIn, fileOutputStream);//备份文件//备份文件
                if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                    sourceFileIn1 = file.getInputStream();
                    FileAESUtils.encryptFile(encryptKey, sourceFileIn1, filePath);
                } else {
                    sourceFileIn1 = file.getInputStream();
                    fileOutputStream1 = new FileOutputStream(new File(filePath));
                    IOUtils.copy(sourceFileIn1, fileOutputStream1);//保存修改后的文件
                    sourceFileIn1.close();
                    fileOutputStream1.close();
                }
            } catch (IOException e) {

            }finally {
                IOUtils.closeQuietly(sourceFileIn);
                IOUtils.closeQuietly(fileOutputStream);
                IOUtils.closeQuietly(sourceFileIn1);
                IOUtils.closeQuietly(fileOutputStream1);
            }
        }
    }

    @RequestMapping(value = "/wpsNotify", method = RequestMethod.POST)
    public void wpsNotify(String attachId, String sessionId, String fileId, Integer eventType, HttpServletRequest request, HttpServletResponse response) {
        if (eventType != null) {
            switch (eventType) {
                case GobalConstant.WPS_NOTIFY_OPEN://打开
                    //锁定编辑的文件，编辑区间其他人不能进行操作
                    if (StringUtils.isNotBlank(fileId)) {
                        Account currentAccount = accountService.getRedisAUserInfoToAccount();
                        PublicFile publicFile = new PublicFile();
                        publicFile.setFileId(fileId);
                        publicFile = publicFileService.selectOnePublicFile(publicFile);
                        publicFile.setIsLock(GobalConstant.FILE_IS_LOCK);

                        Example example = new Example(PublicFile.class);
                        example.createCriteria().andEqualTo("orgId", currentAccount.getOrgId()).andEqualTo("fileId", fileId);
                        publicFileService.updatePublicFile(publicFile, example);
                    }
                    break;
                case GobalConstant.WPS_NOTIFY_UPLOAD://保存上传

                    break;
                case GobalConstant.WPS_NOTIFY_CLOSE://关闭
                    //解锁文件
                    if (StringUtils.isNotBlank(fileId)) {
                        Account currentAccount = accountService.getRedisAUserInfoToAccount();
                        PublicFile publicFile = new PublicFile();
                        publicFile.setFileId(fileId);
                        publicFile = publicFileService.selectOnePublicFile(publicFile);
                        publicFile.setIsLock(GobalConstant.FILE_IS_NOT_LOCK);

                        Example example = new Example(PublicFile.class);
                        example.createCriteria().andEqualTo("orgId", currentAccount.getOrgId()).andEqualTo("fileId", fileId);
                        publicFileService.updatePublicFile(publicFile, example);
                    }
                    break;

                default:
                    break;
            }
        }
    }


    /**
     * @param request
     * @param attach
     * @param openModeType
     * @return ModelAndView
     * @Title: goldgridOpenWord
     * @Description:  金格打开word
     */
    @RequestMapping(value = "/goldgrid/openword", method = RequestMethod.GET)
    public ModelAndView goldgridOpenWord(HttpServletRequest request, Attach attach, String openModeType) {
        ModelAndView mv = new ModelAndView("app/core/kinggrid/openword");
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        attach = attachService.selectOne(attach);
        String mHttpUrlName = request.getRequestURI();
        String mScriptName = request.getServletPath();
        String mServerUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + mHttpUrlName.substring(0, mHttpUrlName.lastIndexOf(mScriptName));//取得OfficeServer文件的完整URL
        mv.addObject("mServerUrl", mServerUrl);
        mv.addObject("sessionId", request.getSession().getId());
        mv.addObject("userName", userInfo.getUserName());
        mv.addObject("attach", attach);
        String pointFlag = "0";
        String downFlag = "0";
        if (openModeType.equals("1")) {
            //只读模式
            mv.addObject("editType", "0");
        } else if (openModeType.equals("2")) {
            //打印模式
            mv.addObject("editType", "0");
            pointFlag = "1";
        } else if (openModeType.equals("3")) {
            //打印模式,下载模式
            mv.addObject("editType", "0");
            pointFlag = "1";
            downFlag = "1";
        } else if (openModeType.equals("4")) {
            //痕迹保留模式
            mv.addObject("editType", "2");
            pointFlag = "1";
        }
        mv.addObject("pointFlag", pointFlag);
        mv.addObject("downFlag", downFlag);
        return mv;
    }

//@RequestMapping(value="/goldgrid/OfficeServer", method=RequestMethod.GET)
//public byte[] OfficeServer(HttpServletRequest request,Attach attach) throws Exception
//{
//	UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
//	attach.setOrgId(userInfo.getOrgId());
//	attach = attachService.selectOne(attach);
//	String filePath = attachpath+attach.getPath();
//	File file = new File(filePath);
//	InputStream instream = new FileInputStream(file);
//	byte[] mFileBody = null;
//	instream.read(mFileBody, 0, Integer.parseInt(attach.getFileSize()+""));
//	instream.close();
//	return mFileBody;
//}


    @RequestMapping(value = "/openppt", method = RequestMethod.GET)
    public ModelAndView openppt(HttpServletRequest request, Attach attach, String openModeType, Map<String, Object> map, NetDisk netDisk, String path) {
        try {
            UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
            //--- PageOffice的调用代码 开始 -----
            PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
            poCtrl.setServerPage("/poserver.zz");//设置授权程序servlet
            poCtrl.setSaveFilePage("/office/pptsave");//设置保存的action
            if (openModeType.equals("4")) {
                if (StringUtils.isBlank(attach.getAttachId())) {
                    poCtrl.webOpen("/sys/file/getFileDown?netDiskId=" + netDisk.getNetDiskId() + "&path=" + URLEncoder.encode(path, "utf-8"), OpenModeType.pptNormalEdit, userInfo.getUserName());
                } else {
                    poCtrl.webOpen("/sys/file/getFileDown?attachId=" + attach.getAttachId(), OpenModeType.pptNormalEdit, userInfo.getUserName());
                }
                poCtrl.addCustomToolButton("保存", "Save()", 1);
            } else if (openModeType.equals("2") || openModeType.equals("3")) {
                if (StringUtils.isBlank(attach.getAttachId())) {
                    poCtrl.webOpen("/sys/file/getFileDown?netDiskId=" + netDisk.getNetDiskId() + "&path=" + URLEncoder.encode(path,"utf-8"), OpenModeType.pptReadOnly, userInfo.getUserName());
                } else {
                    poCtrl.webOpen("/sys/file/getFileDown?attachId=" + attach.getAttachId(), OpenModeType.pptReadOnly, userInfo.getUserName());
                }
                poCtrl.addCustomToolButton("打印", "PrintFile()", 6);
            } else if (openModeType.equals("1")) {
                poCtrl.setAllowCopy(false);//禁止拷贝
                poCtrl.setMenubar(false);//隐藏菜单栏
                if (StringUtils.isBlank(attach.getAttachId())) {
                    poCtrl.webOpen("/sys/file/getFileDown?netDiskId=" + netDisk.getNetDiskId() + "&path=" + URLEncoder.encode(path,"utf-8"), OpenModeType.pptReadOnly, userInfo.getUserName());
                } else {
                    poCtrl.webOpen("/sys/file/getFileDown?attachId=" + attach.getAttachId(), OpenModeType.pptReadOnly, userInfo.getUserName());
                }
            }
            poCtrl.setJsFunction_AfterDocumentOpened("AfterDocumentOpened");
            poCtrl.addCustomToolButton("全屏/还原", "IsFullScreen()", 4);
            //poCtrl.addCustomToolButton("关闭", "CloseFile()", 21);
            map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
            map.put("attachName", attach.getOldName());
            map.put("attachId", attach.getAttachId());
            //--- PageOffice的调用代码 结束 -----
            ModelAndView mv = new ModelAndView("/app/core/office/openppt");
            return mv;
        }catch (Exception e) {
            return new ModelAndView("titps");
        }
    }

    /**
     * @Title: openpdf
     * @Description:  在线打开PDF
     * @param: request
     * @param: attach
     * @param: openModeType
     * @param: map
     * @param: @return
     * @return: ModelAndView
     */
    @RequestMapping(value = "/openpdf", method = RequestMethod.GET)
    public ModelAndView openPdf(HttpServletRequest request, Attach attach, String openModeType, Map<String, Object> map, NetDisk netDisk, String path) {
        try {
            PDFCtrl pdfCtrl1 = new PDFCtrl(request);
            pdfCtrl1.setServerPage(request.getContextPath() + "/poserver.zz"); //此行必须
            pdfCtrl1.addCustomToolButton("隐藏/显示书签", "SetBookmarks()", 0);
            pdfCtrl1.addCustomToolButton("-", "", 0);
            pdfCtrl1.addCustomToolButton("实际大小", "SetPageReal()", 16);
            pdfCtrl1.addCustomToolButton("适合页面", "SetPageFit()", 17);
            pdfCtrl1.addCustomToolButton("适合宽度", "SetPageWidth()", 18);
            pdfCtrl1.addCustomToolButton("-", "", 0);
            pdfCtrl1.addCustomToolButton("首页", "FirstPage()", 8);
            pdfCtrl1.addCustomToolButton("上一页", "PreviousPage()", 9);
            pdfCtrl1.addCustomToolButton("下一页", "NextPage()", 10);
            pdfCtrl1.addCustomToolButton("尾页", "LastPage()", 11);
            pdfCtrl1.addCustomToolButton("-", "", 0);
            pdfCtrl1.addCustomToolButton("向左旋转90度", "SetRotateLeft()", 12);
            pdfCtrl1.addCustomToolButton("向右旋转90度", "SetRotateRight()", 13);
            if (StringUtils.isBlank(attach.getAttachId())) {
                pdfCtrl1.webOpen("/sys/file/getFileDown?netDiskId=" + netDisk.getNetDiskId() + "&path=" + URLEncoder.encode(path, "utf-8"));
            } else {
                pdfCtrl1.webOpen("/sys/file/getFileDown?attachId=" + attach.getAttachId());
            }
            if (openModeType.equals("4")) {
                pdfCtrl1.addCustomToolButton("打印", "PrintFile()", 6);
            } else if (openModeType.equals("2") || openModeType.equals("3")) {
                pdfCtrl1.addCustomToolButton("打印", "PrintFile()", 6);

            } else if (openModeType.equals("1")) {
                pdfCtrl1.setAllowCopy(false);//禁止拷贝
                pdfCtrl1.setMenubar(false);//隐藏菜单栏
                pdfCtrl1.setJsFunction_AfterDocumentOpened("AfterDocumentOpened");
            }
            map.put("pageoffice", pdfCtrl1.getHtmlCode("PDFCtrl1"));
            map.put("attachName", attach.getOldName());
            map.put("attachId", attach.getAttachId());
            //--- PageOffice的调用代码 结束 -----
            ModelAndView mv = new ModelAndView("/app/core/office/openpdf");
            return mv;
        }catch (Exception e) {
        return new ModelAndView("titps");
    }
    }


    /**
     * @Title: openExcel
     * @Description:  打开execl
     * @param: request
     * @param: attach
     * @param: openModeType
     * @param: map
     * @param: @return
     * @return: ModelAndView
     */
    @RequestMapping(value = "/openexcel", method = RequestMethod.GET)
    public ModelAndView openExcel(HttpServletRequest request, Attach attach, String openModeType, Map<String, Object> map, NetDisk netDisk, String path) {
        try {
            UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
            //--- PageOffice的调用代码 开始 -----
            PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
            poCtrl.setServerPage("/poserver.zz");//设置授权程序servlet
            poCtrl.setSaveFilePage("/office/excelsave");//设置保存的action
            if (openModeType.equals("4")) {
                if (StringUtils.isBlank(attach.getAttachId())) {
                    poCtrl.webOpen("/sys/file/getFileDown?netDiskId="+netDisk.getNetDiskId()+"&path="+ URLEncoder.encode(path, "utf-8"), OpenModeType.xlsNormalEdit, userInfo.getUserName());
                }else
                {
                    poCtrl.webOpen("/sys/file/getFileDown?attachId="+attach.getAttachId(), OpenModeType.xlsNormalEdit, userInfo.getUserName());
                }
                poCtrl.addCustomToolButton("保存", "Save()", 1);
            } else if (openModeType.equals("2") || openModeType.equals("3")) {
                if (StringUtils.isBlank(attach.getAttachId())) {
                    poCtrl.webOpen("/sys/file/getFileDown?netDiskId="+netDisk.getNetDiskId()+"&path="+ URLEncoder.encode(path, "utf-8"), OpenModeType.xlsReadOnly, userInfo.getUserName());
                }else
                {
                    poCtrl.webOpen("/sys/file/getFileDown?attachId="+attach.getAttachId(), OpenModeType.xlsReadOnly, userInfo.getUserName());
                }
                poCtrl.addCustomToolButton("打印", "PrintFile()", 6);

            } else if (openModeType.equals("1")) {
                if (StringUtils.isBlank(attach.getAttachId())) {
                    poCtrl.webOpen("/sys/file/getFileDown?netDiskId="+netDisk.getNetDiskId()+"&path="+ URLEncoder.encode(path, "utf-8"), OpenModeType.xlsReadOnly, userInfo.getUserName());
                }else
                {
                    poCtrl.webOpen("/sys/file/getFileDown?attachId="+attach.getAttachId(), OpenModeType.xlsReadOnly, userInfo.getUserName());
                }
                poCtrl.setAllowCopy(false);//禁止拷贝
                poCtrl.setMenubar(false);//隐藏菜单栏
            }
            poCtrl.setJsFunction_AfterDocumentOpened("AfterDocumentOpened");
            poCtrl.addCustomToolButton("全屏/还原", "IsFullScreen()", 4);
            map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));
            map.put("attachName", attach.getOldName());
            map.put("attachId", attach.getAttachId());
            //--- PageOffice的调用代码 结束 -----
            ModelAndView mv = new ModelAndView("/app/core/office/openexcel");
            return mv;
        } catch (Exception e) {
            return new ModelAndView("titps");
        }
    }

    /**
     * @Title: openword
     * @Description:  在线打开word文档
     * @param: request
     * @param: attach
     * @param: openModeType
     * @param: map
     * @param: @return
     * @return: ModelAndView
     */
    @RequestMapping(value = "/openword", method = RequestMethod.GET)
    public ModelAndView openWord(HttpServletRequest request, Attach attach, String openModeType, Map<String, Object> map, NetDisk netDisk, String path) {
        try
        {
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        //--- PageOffice的调用代码 开始 -----
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setServerPage("/poserver.zz");//设置授权程序servlet
        poCtrl.setSaveFilePage("/office/wordsave");//设置保存的action
        if (openModeType.equals("4")) {
            if (StringUtils.isBlank(attach.getAttachId())) {
                poCtrl.webOpen("/sys/file/getFileDown?netDiskId="+netDisk.getNetDiskId()+"&path="+ URLEncoder.encode(path,"utf-8"), OpenModeType.docNormalEdit, userInfo.getUserName());
            }else
            {
                poCtrl.webOpen("/sys/file/getFileDown?attachId="+attach.getAttachId(), OpenModeType.docRevisionOnly, userInfo.getUserName());
            }
            poCtrl.addCustomToolButton("保存", "Save()", 1);
        } else if (openModeType.equals("2") || openModeType.equals("3")) {
            if (StringUtils.isBlank(attach.getAttachId())) {
                poCtrl.webOpen("/sys/file/getFileDown?netDiskId="+netDisk.getNetDiskId()+"&path="+ URLEncoder.encode(path,"utf-8"), OpenModeType.docReadOnly, userInfo.getUserName());
            }else
            {
                poCtrl.webOpen("/sys/file/getFileDown?attachId="+attach.getAttachId(), OpenModeType.docReadOnly, userInfo.getUserName());
            }
            poCtrl.addCustomToolButton("打印", "PrintFile()", 6);
        } else if (openModeType.equals("1")) {
            poCtrl.setAllowCopy(false);//禁止拷贝
            poCtrl.setMenubar(false);//隐藏菜单栏
            if (StringUtils.isBlank(attach.getAttachId())) {
                poCtrl.webOpen("/sys/file/getFileDown?netDiskId="+netDisk.getNetDiskId()+"&path="+ URLEncoder.encode(path,"utf-8"), OpenModeType.docReadOnly, userInfo.getUserName());
            }else
            {
                poCtrl.webOpen("/sys/file/getFileDown?attachId="+attach.getAttachId(), OpenModeType.docReadOnly, userInfo.getUserName());
            }
        }
        poCtrl.setJsFunction_AfterDocumentOpened("AfterDocumentOpened");
        poCtrl.addCustomToolButton("全屏/还原", "IsFullScreen()", 4);
        //poCtrl.addCustomToolButton("关闭", "CloseFile()", 21);
        map.put("pageoffice", poCtrl.getHtmlCode("PageOfficeCtrl1"));

        map.put("attachName", attach.getOldName());
        map.put("attachId", attach.getAttachId());
        //--- PageOffice的调用代码 结束 -----
        ModelAndView mv = new ModelAndView("/app/core/office/openword");
        return mv;
        }catch (Exception e) {
            return new ModelAndView("titps");
        }
    }

    /**
     * @throws Exception
     * @Title: saveFile
     * @Description:  文件保存
     * @param: request
     * @param: response
     * @return: void
     */
    @RequestMapping(value = "/wordsave", method = RequestMethod.POST)
    public void wordSaveFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        FileSaver fs = new FileSaver(request, response);
        String attachId = fs.getFormField("attachId");
        String extName = fs.getFileExtName();
        Attach attach = new Attach();
        attach.setAttachId(attachId);
        attach = attachService.selectOne(attach);
        String filePath = attachpath+attach.getPath();
        String oldPath = attach.getPath();
        File file = new File(filePath);
        filePath = file.getAbsoluteFile().toString();
        String sourceFilePath = filePath;
        int dot = filePath.lastIndexOf('.');
        if (!extName.isEmpty()) {
            dot = filePath.lastIndexOf('.');
            if ((dot > -1) && (dot < (filePath.length()))) {
                filePath = filePath.substring(0, dot);
            }
            filePath = filePath + extName;
        }
        //备份修改前的文件版本
        String oldName = SysTools.randFileName(attach.getOldName());
        oldPath = oldPath.substring(0, oldPath.lastIndexOf(File.separator)) + File.separator + oldName;
        Attach oldAttach = new Attach();
        BeanUtils.copyProperties(attach, oldAttach);
        oldAttach.setAttachId(SysTools.getGUID());
        oldAttach.setNewName(oldName);
        oldAttach.setPath(oldPath);
        oldAttach.setSourceAttachId(attachId);
        attachService.insert(oldAttach);
        //更新最新文件版本
        String encryptKey = "";
        if (encryption.equals("1")) {
            encryptKey = FileAESUtils.getSecretKey();
        }
        int oldVersion = Integer.parseInt(attach.getVersion().replace(".", ""));
        String newVersion = StringUtils.join(String.valueOf(oldVersion + 1).toCharArray(), '.');
        attach.setVersion(newVersion);
        attach.setExtName(extName);
        attach.setOldName(attach.getOldName().substring(0, attach.getOldName().lastIndexOf(".")) + extName);
        attach.setNewName(attach.getNewName().substring(0, attach.getNewName().lastIndexOf(".")) + extName);
        attach.setEncryptKey(encryptKey);
        attach.setFileSize(Long.valueOf(fs.getFileSize()));
        attach.setCreateAccount(userInfo.getAccountId());
        attach.setUpTime(SysTools.getTime("yyyy-MM-dd HH:mm:ss"));
        Example example = new Example(Attach.class);
        example.createCriteria().andEqualTo("orgId", userInfo.getOrgId()).andEqualTo("attachId", attach.getAttachId());
        attachService.updateAttach(attach, example);
        FileOutputStream fileOutputStream = null;
        FileInputStream sourceFileIn = null;
        try {
            sourceFileIn = new FileInputStream(new File(sourceFilePath));
            fileOutputStream = new FileOutputStream(new File(attachpath+oldPath));
            IOUtils.copy(sourceFileIn, fileOutputStream);//备份文件
            if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                InputStream sourceFileIn1 = fs.getFileStream();
                FileAESUtils.encryptFile(encryptKey, sourceFileIn1, filePath);
            } else {
                //保存修改后的文件
                fs.saveToFile(filePath);
            }
            fs.close();
        } catch (IOException e) {
            //e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(sourceFileIn);
            IOUtils.closeQuietly(fileOutputStream);
        }

    }

    /**
     * @throws Exception
     * @Title: excelSaveFile
     * @Description:  保存execl
     * @param: request
     * @param: response
     * @return: void
     */
    @RequestMapping(value = "/excelsave", method = RequestMethod.POST)
    public void excelSaveFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        FileSaver fs = new FileSaver(request, response);
        String extName = fs.getFileExtName();
        String attachId = fs.getFormField("attachId");
        Attach attach = new Attach();
        attach.setAttachId(attachId);
        attach = attachService.selectOne(attach);
        String filePath = attachpath+attach.getPath();
        String oldPath = attach.getPath();
        File file = new File(filePath);
        filePath = file.getAbsoluteFile().toString();
        String sourceFilePath = filePath;
        int dot = filePath.lastIndexOf('.');
        if (!extName.isEmpty()) {
            dot = filePath.lastIndexOf('.');
            if ((dot > -1) && (dot < (filePath.length()))) {
                filePath = filePath.substring(0, dot);
            }
            filePath = filePath + extName;
        }
        //备份修改前的文件版本
        String oldName = SysTools.randFileName(attach.getOldName());
        oldPath = oldPath.substring(0, oldPath.lastIndexOf(File.separator)) + File.separator + oldName;
        Attach oldAttach = new Attach();
        BeanUtils.copyProperties(attach, oldAttach);
        oldAttach.setAttachId(SysTools.getGUID());
        oldAttach.setNewName(oldName);
        oldAttach.setPath(oldPath);
        oldAttach.setSourceAttachId(attachId);
        attachService.insert(oldAttach);
        //更新最新文件版本
        int oldVersion = Integer.parseInt(attach.getVersion().replace(".", ""));
        String encryptKey = "";
        if (encryption.equals("1")) {
            encryptKey = FileAESUtils.getSecretKey();
        }
        String newVersion = StringUtils.join(String.valueOf(oldVersion + 1).toCharArray(), '.');
        attach.setVersion(newVersion);
        attach.setExtName(extName);
        attach.setOldName(attach.getOldName().substring(0, attach.getOldName().lastIndexOf(".")) + extName);
        attach.setNewName(attach.getNewName().substring(0, attach.getNewName().lastIndexOf(".")) + extName);
        attach.setFileSize(Long.valueOf(fs.getFileSize()));
        attach.setCreateAccount(userInfo.getAccountId());
        attach.setUpTime(SysTools.getTime("yyyy-MM-dd HH:mm:ss"));
        attach.setEncryptKey(encryptKey);
        Example example = new Example(Attach.class);
        example.createCriteria().andEqualTo("orgId", userInfo.getOrgId()).andEqualTo("attachId", attach.getAttachId());
        attachService.updateAttach(attach, example);
        FileInputStream sourceFileIn = null;
        FileOutputStream fileOutputStream = null;
        try {
            sourceFileIn = new FileInputStream(new File(sourceFilePath));
            fileOutputStream = new FileOutputStream(new File(attachpath+oldPath));
            IOUtils.copy(sourceFileIn, fileOutputStream);//备份文件
            if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                InputStream sourceFileIn1 = fs.getFileStream();
                FileAESUtils.encryptFile(encryptKey, sourceFileIn1, filePath);
            } else {
                //保存修改后的文件
                fs.saveToFile(filePath);
            }
            fs.close();
        } catch (IOException e) {

        }finally {
            IOUtils.closeQuietly(sourceFileIn);
            IOUtils.closeQuietly(fileOutputStream);
        }
    }

    /**
     * @throws Exception
     * @Title: pptSaveFile
     * @Description:  保存ppt
     * @param: request
     * @param: response
     * @return: void
     */
    @RequestMapping(value = "/pptsave", method = RequestMethod.POST)
    public void pptSaveFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserInfo userInfo = accountService.getRedisAUserInfoToUserInfo();
        FileSaver fs = new FileSaver(request, response);
        String extName = fs.getFileExtName();
        String attachId = fs.getFormField("attachId");
        Attach attach = new Attach();
        attach.setAttachId(attachId);
        attach = attachService.selectOne(attach);
        String filePath = attach+attach.getPath();
        String oldPath = attach.getPath();
        File file = new File(filePath);
        filePath = file.getAbsoluteFile().toString();
        String sourceFilePath = filePath;
        int dot = filePath.lastIndexOf('.');
        if (!extName.isEmpty()) {
            dot = filePath.lastIndexOf('.');
            if ((dot > -1) && (dot < (filePath.length()))) {
                filePath = filePath.substring(0, dot);
            }
            filePath = filePath + extName;
        }
        //备份修改前的文件版本
        String oldName = SysTools.randFileName(attach.getOldName());
        oldPath = oldPath.substring(0, oldPath.lastIndexOf(File.separator)) + File.separator + oldName;
        Attach oldAttach = new Attach();
        BeanUtils.copyProperties(attach, oldAttach);
        oldAttach.setAttachId(SysTools.getGUID());
        oldAttach.setNewName(oldName);
        oldAttach.setPath(oldPath);
        oldAttach.setSourceAttachId(attachId);
        attachService.insert(oldAttach);
        //更新最新文件版本
        String encryptKey = "";
        if (encryption.equals("1")) {
            encryptKey = FileAESUtils.getSecretKey();
        }
        int oldVersion = Integer.parseInt(attach.getVersion().replace(".", ""));
        String newVersion = StringUtils.join(String.valueOf(oldVersion + 1).toCharArray(), '.');
        attach.setVersion(newVersion);
        attach.setExtName(extName);
        attach.setOldName(attach.getOldName().substring(0, attach.getOldName().lastIndexOf(".")) + extName);
        attach.setNewName(attach.getNewName().substring(0, attach.getNewName().lastIndexOf(".")) + extName);
        attach.setPath(filePath);
        attach.setEncryptKey(encryptKey);
        attach.setFileSize(Long.valueOf(fs.getFileSize()));
        attach.setCreateAccount(userInfo.getAccountId());
        attach.setUpTime(SysTools.getTime("yyyy-MM-dd HH:mm:ss"));
        Example example = new Example(Attach.class);
        example.createCriteria().andEqualTo("orgId", userInfo.getOrgId()).andEqualTo("attachId", attach.getAttachId());
        attachService.updateAttach(attach, example);
        FileInputStream sourceFileIn = null;
        FileOutputStream fileOutputStream = null;
        try {
            sourceFileIn = new FileInputStream(new File(sourceFilePath));
            fileOutputStream = new FileOutputStream(new File(attachpath+oldPath));
            IOUtils.copy(sourceFileIn, fileOutputStream);//备份文件
            //保存修改后的文件
            if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                InputStream sourceFileIn1 = fs.getFileStream();
                FileAESUtils.encryptFile(encryptKey, sourceFileIn1, filePath);
            } else {
                fs.saveToFile(filePath);
            }
            fs.close();
        } catch (IOException e) {

        }finally {
            IOUtils.closeQuietly(sourceFileIn);
            IOUtils.closeQuietly(fileOutputStream);
        }
    }

    /**
     * OnlyOffice文件保存
     *
     * @param request
     * @param response
     */
    @RequestMapping("/saveOnlyOfficeFile")
    public void saveWord(HttpServletRequest request, HttpServletResponse response) {
        String accountId = request.getParameter("accountId");
        String attachId = request.getParameter("attachId");
        String orgId = request.getParameter("orgId");
        PrintWriter writer = null;
        FileInputStream sourceFileIn = null;
        FileOutputStream fileOutputStream = null;
        FileOutputStream fileOutputStream1 = null;
        InputStream stream = null;
        try {
            writer = response.getWriter();
            String body = "";
            try {
                Scanner scanner = new Scanner(request.getInputStream());
                scanner.useDelimiter("\\A");
                body = scanner.hasNext() ? scanner.next() : "";
                scanner.close();
            } catch (Exception ex) {
                writer.write("get request.getInputStream error:" + ex.getMessage());
                return;
            }
            if (body.isEmpty()) {
                writer.write("empty request.getInputStream");
                return;
            }
            JSONObject jsonObj = JSON.parseObject(body);
            int status = (Integer) jsonObj.get("status");
            int saved = 0;
            if (status == 2 || status == 3 || status == 6) //MustSave, Corrupted
            {
                String downloadUri = (String) jsonObj.get("url");
                try {
                    URL url = new URL(downloadUri);
                    java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                    stream = connection.getInputStream();
                    if (stream == null) {
                        throw new Exception("Stream is null");
                    }
                    Attach attach = new Attach();
                    attach.setOrgId(orgId);
                    attach.setAttachId(attachId);
                    attach = attachService.selectOne(attach);
                    String extName = attach.getExtName();
                    String filePath = attachpath + attach.getPath();
                    String oldPath = attach.getPath();
                    File targetFile = new File(filePath);
                    filePath = targetFile.getAbsoluteFile().toString();
                    String sourceFilePath = filePath;
                    //备份修改前的文件版本
                    String oldName = SysTools.randFileName(attach.getOldName());
                    oldPath = oldPath.substring(0, oldPath.lastIndexOf(File.separator)) + File.separator + oldName;
                    Attach oldAttach = new Attach();
                    BeanUtils.copyProperties(attach, oldAttach);
                    oldAttach.setAttachId(SysTools.getGUID());
                    oldAttach.setNewName(oldName);
                    oldAttach.setPath(oldPath);
                    oldAttach.setSourceAttachId(attachId);
                    attachService.insert(oldAttach);
                    //更新最新文件版本
                    String encryptKey = "";
                    if (encryption.equals("1")) {
                        encryptKey = FileAESUtils.getSecretKey();
                    }
                    int oldVersion = Integer.parseInt(attach.getVersion().replace(".", ""));
                    String newVersion = StringUtils.join(String.valueOf(oldVersion + 1).toCharArray(), '.');
                    attach.setVersion(newVersion);
                    attach.setExtName(extName);
                    attach.setFileSize(Long.valueOf(stream.available()));
                    attach.setOldName(attach.getOldName().substring(0, attach.getOldName().lastIndexOf(".")) + extName);
                    attach.setNewName(attach.getNewName().substring(0, attach.getNewName().lastIndexOf(".")) + extName);
                    attach.setEncryptKey(encryptKey);
                    attach.setCreateAccount(accountId);
                    attach.setUpTime(SysTools.getTime("yyyy-MM-dd HH:mm:ss"));
                    Example example = new Example(Attach.class);
                    example.createCriteria().andEqualTo("orgId", orgId).andEqualTo("attachId", attach.getAttachId());
                    attachService.updateAttach(attach, example);
                    try {
                        sourceFileIn = new FileInputStream(new File(sourceFilePath));
                        fileOutputStream = new FileOutputStream(new File(attachpath + oldPath));
                        IOUtils.copy(sourceFileIn, fileOutputStream);//备份文件//备份文件
                        sourceFileIn.close();
                        fileOutputStream.close();
                        if (StringUtils.isNotBlank(attach.getEncryptKey())) {
                            FileAESUtils.encryptFile(encryptKey, stream, filePath);
                        } else {
                            fileOutputStream1 = new FileOutputStream(new File(filePath));
                            IOUtils.copy(stream, fileOutputStream1);//保存修改后的文件
                            stream.close();
                        }
                    } catch (IOException e) {

                    }
                    connection.disconnect();
                } catch (Exception ex) {
                    saved = 1;
                    ex.printStackTrace();
                }
            }
            writer.write("{\"error\":" + saved + "}");
        } catch (IOException e) {
            JSONObject json = new JSONObject();
            json.put("error", "-1");
            writer.write(json.toString());
        }finally {
            IOUtils.closeQuietly(stream);
            IOUtils.closeQuietly(sourceFileIn);
            IOUtils.closeQuietly(fileOutputStream);
            IOUtils.closeQuietly(fileOutputStream1);
        }
    }
}
